package com.cyt.chattlibrary.message;

import android.os.Parcel;

import com.cyt.chattlibrary.face.SmileyParser;
import com.cyt.chattlibrary.message.model.MessageContent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * @author QiQi
 * @ClassName: TextMessage
 * @date 2018/10/20
 * @description
 */
public class TextMessage extends MessageContent {
    private String content;

    @Override
    public byte[] encode() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("content", getContent());
            if (getJSONUserInfo() != null) {
                jsonObject.put("user", getJSONUserInfo());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            return jsonObject.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    public TextMessage(byte[] data) {
        String jsonStr = null;
        try {
            jsonStr = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            if (jsonObject.has("content")) {
                setContent(jsonObject.optString("content"));
            }

            if (jsonObject.has("user")) {
                setUserInfo(parseJsonToUserInfo(jsonObject.optJSONObject("user")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static TextMessage obtain(String text) {
        TextMessage model = new TextMessage();
        model.setContent(SmileyParser.getInstance().getExpressionString(text));
        return model;
    }



    public String getContent() {
        return content == null ? "" : content;
    }

    public void setContent(String content) {
        this.content = content;
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.content);
    }

    public TextMessage() {
    }

    protected TextMessage(Parcel in) {
        this.content = in.readString();
    }

    public static final Creator<TextMessage> CREATOR = new Creator<TextMessage>() {
        @Override
        public TextMessage createFromParcel(Parcel source) {
            return new TextMessage(source);
        }

        @Override
        public TextMessage[] newArray(int size) {
            return new TextMessage[size];
        }
    };
}
